package com.bidcms.web;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.bidcms.util.Config;
import com.google.gson.Gson;

import freemarker.template.SimpleScalar;

public class BaseController  implements ServletContextAware, Serializable{
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	
	protected ServletContext        servletContext;
	protected WebApplicationContext applicationContext;
	
	@Autowired
	private Config cfg;
	
	@Autowired
	protected HttpServletRequest request;
	
	public void addGlobalAttrs(ModelAndView mv){
		//bidcms_uid
		//shop
		//bidcms .tunnel.php or.me
		//http://bidcms.tunnel.phpor.me
		//http://bidcms.tunnel.phpor.me
		//http://bidcms.tunnel.phpor.me/
		mv.addObject("base", "{\"bid_id\":1,\"user_id\":1,\"run_mode\":\"online\",\"debug\":false,\"project\":\"default\",\"online_debug\":true,\"js\":{\"js_compress\":true,\"css_compress\":true,\"use_js_cdn\":true,\"use_css_cdn\":true,\"message_report\":true,\"checkbrowser\":true,\"hide_wx_nav\":true,\"qn_public\":\"kdt_img\",\"qn_private\":\"kdt-private\"},\"full_action\":\"getIndexHtml\",\"method\":\"get\",\"format\":\"html\",\"account\":null,\"sign\":null,\"nick_name\":null,\"gender\":null,\"avatar\":\"http://bidcms.tunnel.phpor.me/fesco-web/static/v2/image/avatar.png\",\"team_admin\":{\"level\":1},\"is_new_weixin_pay\":0,\"auth_new\":false,\"platform\":\"unknown\",\"is_mobile\":true,\"ajaxURL\":{\"isFans\":\"http://bidcms.com/v1/api/fans/check?fans_mi=0\"},\"logURL\":\"http://bidcms.tunnel.phpor.me/fesco-web/static/v2/image/1.gif\",\"alipay_env\":true,\"wxpay_env\":false,\"wxaddress_env\":false,\"isShopDomain\":false,\"source\":\"\",\"track\":\"\",\"mp_changed\":false,\"nobody\":\"5445c3ddf2ed4\",\"hide_shopping_cart\":0,\"no_sidebar\":0,\"page_size\":320,\"spm\":{\"logType\":\"f\",\"logId\":\"45\"}}");
		mv.addObject("mp_data", "[]");
		mv.addObject("team_status", "{\"weixin_server\":0}");
		mv.addObject("shopName", "你懂的");
		mv.addObject("shoplogo", "static/v2/image/shop.png");
		mv.addObject("url", new Gson().toJson(cfg));
	}
	
	public String getRealPath(HttpServletRequest req,String folderName){
		return req.getSession().getServletContext().getRealPath(folderName);
	}
	
	/**
	 * 获取连接的IP地址
	 */
	protected String getClientIpAddr() {
		//HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		final String UNKNOWN = "unknown";
		String ip = request.getHeader("x-forwarded-for");
		if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("Proxy-Client-IP");
		if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("WL-Proxy-Client-IP");
		if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getRemoteAddr();
		return ip;
	}
	public SimpleScalar getFreeMarkerVar(String varName){
		 return (SimpleScalar) freeMarkerConfigurer
			.getConfiguration().getSharedVariable(varName);
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
		this.applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, String> getAllRequestParam(HttpServletRequest request) throws Exception{
		Map res = new HashMap();
		request.setCharacterEncoding("ISO-8859-1");
	    Enumeration temp = request.getParameterNames();
	    while ((null != temp) && (temp.hasMoreElements())) {
	      String en = (String)temp.nextElement();
	      String value = request.getParameter(en);
	      if ( StringUtils.isNotBlank(value)){
	    	  res.put(en, value);
	      }
	    }
	    return res;
	}
	
	public void addPageParams(Integer p,Integer pageSize,Map<String,Object> param){
		int start = 0;
		int end = 0;
		start = (p-1)*pageSize;
		end = start + pageSize;
		param.put("start", start);
		param.put("end", end);
	}
	
}
